package com.jhgsys.internal.sypq.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.sypq.entity.Customer;
import com.jhgsys.internal.sypq.service.ICustomerService;
import com.jhgsys.internal.system.entity.User;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.Random;

/**
 * 客户信息 Controller
 *
 * @author ganjun
 * @date 2024-11-12 14:15:30
 */
@Slf4j
@Validated
@Controller
public class CustomerController extends BaseController {

    @Autowired
    private ICustomerService customerService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "customer")
    @RequiresPermissions("customer:view")
    public String customerIndex(Model model){
        boolean isAdmin = hasHeadCompanyRole();
        model.addAttribute("isAdmin", isAdmin);
        return jumpPage("sypq/customer/customerList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "customer/add")
    @RequiresPermissions("customer:add")
    public String customerAdd(Model model){
        String dateStr = DateUtil.getDateFormat(new Date(), "yyyyMM");
        Random random = new Random();
        int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
        String cmNo = "CM" + dateStr + String.format("%04d", randomNumber); // 格式化为四位数字
        model.addAttribute("cmNo", cmNo);
        return jumpPage("sypq/customer/customerEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "customer/update/{id}")
    @RequiresPermissions("customer:edit")
    public String customerUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("customer", customerService.findCustomerById(id));
        return jumpPage("sypq/customer/customerEdit");
    }

    /**
     * 到审核页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "customer/audit/{id}")
    @RequiresPermissions("customer:audit")
    public String customerAudit(Model model, @PathVariable("id") String id){
        model.addAttribute("customer", customerService.findCustomerById(id));
        return jumpPage("sypq/customer/customerAudit");
    }

    /**
     * 到查看原因页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "customer/viewReason/{id}")
    @RequiresPermissions("customer:audit")
    public String customerViewReason(Model model, @PathVariable("id") String id){
        model.addAttribute("reason", customerService.findCustomerById(id));
        return jumpPage("sypq/customer/viewReason");
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @GetMapping("customer")
    @ResponseBody
    @RequiresPermissions("customer:view")
    public FebsResponse getAllCustomers(Customer customer) {
        try {
            return success(customerService.findCustomerList(customer));
        }catch (Exception ex){
            return failure(ex);
        }

    }

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @GetMapping("customer/list")
    @ResponseBody
    @RequiresPermissions("customer:view")
    public FebsResponse customerList(QueryRequest request, @Param("nameSearch") String nameSearch,
                                     @Param("contactSearch") String contactSearch, @Param("statusSearch") String statusSearch) {
        try {
            //判断是否系统管理员
//            boolean isAdmin = hasHeadCompanyRole();
            String userName = "";
//            if(isAdmin){
//                userName = getCurrentUser().getUserName();
//            }
            Map<String, Object> dataTable = getDataTable(this.customerService.findCustomerPage(request, nameSearch,
                    contactSearch, statusSearch, userName));
            return success(dataTable);
        }catch (Exception ex){
            return failure(ex);
        }
    }

    /**
     * 导出
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @GetMapping("customer/export")
//    @ResponseBody
    @RequiresPermissions("customer:export")
    public void export(String nameSearch, String contactSearch, String statusSearch, HttpServletResponse response) throws FebsException {
        try {
            Customer custParams = new Customer();
            custParams.setCustName(nameSearch);
            custParams.setContact(contactSearch);
            if(StringUtils.isNotBlank(statusSearch)){
                custParams.setStatus(Integer.parseInt(statusSearch));
            }
            List<Customer> custList = customerService.findCustomerList(custParams);
            ExcelKit.$Export(Customer.class, response).downXlsx(custList, false);
        }catch (Exception ex){
            String message = "导出Excel失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }

    /**
     * 新增 Customer
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @Log("新增Customer")
    @PostMapping("customer")
    @ResponseBody
    @RequiresPermissions("customer:add")
    public FebsResponse addCustomer(@Valid @RequestBody Customer customer) throws FebsException {
        try {
            this.customerService.createCustomer(customer);
            return success();
        } catch (Exception ex) {
            return failure(ex,"新增失败");
        }
    }

    /**
     * 逻辑删除 Customer
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @Log("逻辑删除Customer")
    @GetMapping("customer/delete/{id}")
    @ResponseBody
    @RequiresPermissions("customer:delete")
    public FebsResponse deleteCustomer(@PathVariable("id") String customerIds) throws FebsException {
        try {
            Customer customer = new Customer();
            customer.setDeletedBy(getCurrentUser().getUserName());
            customer.setDeletedTime(new Date());
            customer.setDeletedFlg(FebsConstant.INVALID);
            this.customerService.deleteCustomer(customer,customerIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
    * 物理删除 Customer
    * @author ganjun
    * @date 2024-11-12 14:15:30
    */
    @Log("物理删除Customer")
    @GetMapping("customer/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("customer:delete")
    public FebsResponse physicallyDeleteCustomer(@PathVariable("id") String customerIds) throws FebsException {
        try {
            this.customerService.physicallyDeleteCustomer(customerIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
     * 修改 Customer
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @Log("修改Customer")
    @PostMapping("customer/update")
    @ResponseBody
    @RequiresPermissions("customer:edit")
    public FebsResponse updateCustomer(@RequestBody Customer customer) throws FebsException {
        try {
            this.customerService.updateCustomer(customer);
            return success();
        } catch (Exception ex) {
            return failure(ex,"修改失败");
        }
    }

    /**
     * 审核 Customer
     * @author ganjun
     * @date 2024-11-12 14:15:30
     */
    @Log("审核Customer")
    @PostMapping("customer/audit")
    @ResponseBody
    @RequiresPermissions("customer:audit")
    public FebsResponse auditCustomer(@RequestBody Customer customer) throws FebsException {
        try {
            this.customerService.auditCustomer(customer);
            return success();
        } catch (Exception ex) {
            return failure(ex,"审核失败");
        }
    }

}
